package com.itheima.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.GoodsMapper;
import com.itheima.pojo.Goods;
import com.itheima.service.GoodsService;
import com.itheima.utils.RedisUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public boolean deduckStore(Long goodId, Integer num) {
        String key = "goods:deduck:" + goodId;
        //setIfAbsent 对应redis原生的setnx
        //锁失效
        //锁续命 ttl 30 10 30
//        boolean lock = redisTemplate.opsForValue().setIfAbsent(key,goodId,30L, TimeUnit.SECONDS);
//        while (lock == false){
//            lock = redisTemplate.opsForValue().setIfAbsent(key,goodId,30L, TimeUnit.SECONDS);
//            try {
//                Thread.sleep(10);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        }
        try {
            RedisUtil.lock(key);
            //45s
            Goods goods = this.baseMapper.selectById(goodId);
            if(goods.getStokeNum() >= num){//判断是否可以进去扣减库存
                goods.setStokeNum(goods.getStokeNum() - num);
                this.updateById(goods);
            }
        }finally {
//            redisTemplate.delete(key);
            RedisUtil.unlock(key);
        }
        return true;
    }
}
